package com.erpanderp.wam.tm.view;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.SwingWorker;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import com.erpanderp.wam.tm.model.entity.RecruitmentProfile;
import com.erpanderp.wam.tm.model.entity.RecruitmentRequest;
import com.erpanderp.wam.tm.model.service.RRFDAO;
import com.erpanderp.wam.tm.model.service.RecruitmentProfileDAO;
import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.EmailUtil;
import com.erpanderp.wam.util.WAMHostManager;

@ManagedBean
@ViewScoped
public class ManagerShortListProfilesBean  implements Serializable{
	
	private static final long serialVersionUID = 1L;
	private HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
	private HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
	private ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
	private WAMUser wamUser = (WAMUser) session.getAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSER);
	
	private Map<String,String> shortListedMap = CommonLookup.getAuthenticationsMap();
	private Map<String,String> interviewModeMap = CommonLookup.getInterviewMode();	
	private List<RecruitmentProfile> recruitmentProfiles = new ArrayList<RecruitmentProfile>();
	
	private RecruitmentProfileDAO recruitmentProfileDAO=new RecruitmentProfileDAO();
	private RRFDAO rrfDAO = new RRFDAO();
	
	private RecruitmentRequest recruitmentRequest = new RecruitmentRequest();
	private RecruitmentProfile recruitmentProfile ;
	
	private EmailUtil emailUtil;
	private String EMAIL_MESSAGE;	
	private String rrfCode;
	private StreamedContent file; 
	
	private boolean renderBackButton; 
	private boolean renderCloseButton;
	
	private int sno=1;
	
	public ManagerShortListProfilesBean() {	
		
		if(wamUser != null){
			renderBackButton = true;
		}else{
			renderCloseButton=true;
		}
	  rrfCode=request.getParameter("rrfCode");
	  System.out.println("rrfCode======IN CONSTR======"+rrfCode);
	  recruitmentProfiles = recruitmentProfileDAO.getAllProfilesByRRFCode(rrfCode);
	  System.out.println("recruitmentProfiles==============="+recruitmentProfiles.size());
	  for(RecruitmentProfile recruitmentProfile : recruitmentProfiles){
		  recruitmentProfile.setSno(sno);
		  sno++;
	  }
	  System.out.println("Serial no finally::::::::"+sno);
	  recruitmentRequest = rrfDAO.getRRFByRecruitmentRequestCode(rrfCode);
	}
	
	//SHORT RESOURCES ACTION
	public void shortListResourcesAction(ActionEvent e1) {			
		try{
			   if (recruitmentProfiles.size() > 0 ) {	
				    System.out.println("INSIDE ACTION LISTENER METHOD::::::::");
				    System.out.println("recruitmentRequest:::OBJ:::::"+recruitmentRequest);
				    recruitmentRequest.setRecritmentStatus("SHORTLISTED BY MANAGER");
				    rrfDAO.updateRRFRequest(recruitmentRequest);
					recruitmentProfileDAO.saveRecruitmentProfiles(recruitmentProfiles);
					System.out.println("AT CALLER METHOD: " + sendMessage());
					FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_INFO, "Resources are shortlisted successfully.", ""));
		       }
				
			   
		}catch (Exception e) {
			e.printStackTrace();
			FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed to shortlist Resources.", e.getMessage()));
		}
	}
	
	//FILE DOWNLOAD ACTION
		public void fileDownload(ActionEvent e) throws FileNotFoundException{
			Map<String,String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
			String candidateEmail = params.get("candidateEmail");
			System.out.println("filePath FROM PARAM = "+candidateEmail);
			recruitmentProfile = recruitmentProfileDAO.getRecruitmentProfileByCandidateEmail(candidateEmail);	
			ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();        
		    File result = new File(extContext.getRealPath("//RRFResumes//"+recruitmentProfile.getUploadFilePath()));        
		    InputStream stream = new FileInputStream(result.getAbsolutePath());
		    setFile(new DefaultStreamedContent(stream, "application/msword","ERPandERPDBProfile"));		
		}
		
	//SENDING EMAIL 
	public String sendMessage(){
		Map<String, String> hostsMap = WAMHostManager.getWAMHosts(context);
		String domainName = context.getInitParameter("domainName");
		
		emailUtil = new EmailUtil();
		if (hostsMap.get(CommonLookup.DEV_EMAIL) == null) {
			System.out.println("PRODUCTION");
			String[] to = { recruitmentRequest.getRecruiter().getEmail() };
			emailUtil.setRecieverAddresses(to);			
		} else {
			System.out.println("DEVELOPMENT");
			String[] to = { hostsMap.get(CommonLookup.DEV_EMAIL) };
			emailUtil.setRecieverAddresses(to);			
		}
		
		String requestURL = "tm/scheduleinterviews.html?rrfCode=" + rrfCode+"&activity=ScheduleByRecruiter";
		String privateLink = "http://" + hostsMap.get(CommonLookup.PRIVATEHOST) + "/" + domainName + "/" + requestURL;
		String publicLink = "http://" + hostsMap.get(CommonLookup.PUBLICHOST) + "/"	+ domainName + "/" + requestURL;
		SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
		String messageString = "Dear " + recruitmentRequest.getRecruiter().getFirstName() + " " + recruitmentRequest.getRecruiter().getLastName() + "" +
								",<br /><br />" +
								
								"<table style='border: 1px solid #d9d9d9;'>" +
						        "<tr> <td>Recruitment Request Code </td><td> : </td><td>" + rrfCode+ " </td></tr>" +
						        "<tr> <td>Technology</td><td> : </td> <td>" + recruitmentRequest.getTechnology().getDisplayName() + " </td></tr>" +						       
						        "</table><br/>"+	
						        "<b>Please check with the candidates and schedule interview date and times</b><br/><br/>"+
						        "<a style='color:#FF9933;font-weight: bold;' href=\""+
						        privateLink + "\">" + "Please click here to schedule candidate available time" + "</a /><br />"+
								"(Employees who are in Hyderabad office)"+"<br /><br />"+
								"<a style='color:#FF9933;font-weight: bold;' href=\""+
								publicLink + "\">" + "Please click here to schedule candidate available time" + "</a /><br />"+
								"(out side Hyderabad office)"+"<br /><br />"+
								
								"Thanks & Regards, <br />"+CommonLookup.WAM_DEVTEAM_SIGNATURE;;
		
		emailUtil.setMessage(messageString);
		emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");
		emailUtil.setSubject("WAM - RRF Request (" + rrfCode + ")- Schedule Candidate Available Time");

		SwingWorker worker = new SwingWorker<String, Object>() {
			@Override
			protected String doInBackground() throws Exception {
				EMAIL_MESSAGE = emailUtil.processAndSendEmail();
				return null;
			}

			@Override
			protected void done() {
					System.out.println("DONE " + EMAIL_MESSAGE);		
			}
		};
		worker.execute();
		System.out.println( "BEFORE RETURNING: " + EMAIL_MESSAGE);
		return EMAIL_MESSAGE;
	}
	//SETTERS AND GETTER METHODS
	public List<RecruitmentProfile> getRecruitmentProfiles() {
		return recruitmentProfiles;
	}

	public void setRecruitmentProfiles(List<RecruitmentProfile> recruitmentProfiles) {
		this.recruitmentProfiles = recruitmentProfiles;
	}

	public RecruitmentProfileDAO getRecruitmentProfileDAO() {
		return recruitmentProfileDAO;
	}

	public void setRecruitmentProfileDAO(RecruitmentProfileDAO recruitmentProfileDAO) {
		this.recruitmentProfileDAO = recruitmentProfileDAO;
	}

	public Map<String,String> getShortListedMap() {
		return shortListedMap;
	}

	public void setShortListedMap(Map<String,String> shortListedMap) {
		this.shortListedMap = shortListedMap;
	}

	public Map<String,String> getInterviewModeMap() {
		return interviewModeMap;
	}

	public void setInterviewModeMap(Map<String,String> interviewModeMap) {
		this.interviewModeMap = interviewModeMap;
	}

	public RecruitmentRequest getRecruitmentRequest() {
		return recruitmentRequest;
	}

	public void setRecruitmentRequest(RecruitmentRequest recruitmentRequest) {
		this.recruitmentRequest = recruitmentRequest;
	}

	public WAMUser getWamUser() {
		return wamUser;
	}

	public void setWamUser(WAMUser wamUser) {
		this.wamUser = wamUser;
	}

	public boolean isRenderBackButton() {
		return renderBackButton;
	}

	public void setRenderBackButton(boolean renderBackButton) {
		this.renderBackButton = renderBackButton;
	}

	public boolean isRenderCloseButton() {
		return renderCloseButton;
	}

	public void setRenderCloseButton(boolean renderCloseButton) {
		this.renderCloseButton = renderCloseButton;
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

}
